using System.IO;
using QFramework.Framework.ResKit;
using QFramework.Framework.ResKit.HotUpdate;
using UnityEditor;
using UnityEngine;

namespace QFramework.Example._11.AssetBundleExample
{
    public class AssetBundleExample : MonoBehaviour
    {
        private AssetBundle _bundle;
        private ResLoader _resLoader = new();

        private void Start()
        {
            HotUpdateMgr.Instance.CheckState(() =>
            {
                _bundle = _resLoader.LoadSync<AssetBundle>("gameobject");

                var gameObj = _bundle.LoadAsset<GameObject>("GameObject");

                Instantiate(gameObj);
            });
        }

        private void OnDestroy()
        {
            _resLoader.ReleaseAll();
            _resLoader = null;
        }

#if UNITY_EDITOR
        [MenuItem("QFramework/Example/11.AssetBundleExample/Build AssetBundle", false, 11)]
        private static void MenuClicked()
        {
            if (!Directory.Exists(Application.streamingAssetsPath))
                Directory.CreateDirectory(Application.streamingAssetsPath);

            BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath,
                BuildAssetBundleOptions.None,
                BuildTarget.StandaloneWindows);
        }

        [MenuItem("QFramework/Example/11.AssetBundleExample/Run", false, 11)]
        private static void MenuClicked2()
        {
            EditorApplication.isPlaying = true;
            new GameObject("AssetBundleExample").AddComponent<AssetBundleExample>();
        }
#endif
    }
}